import React, { useState, useEffect } from 'react';
import { Card, Button, message } from 'antd';
import axios from 'axios';
import { useParams } from 'react-router-dom';
import { Col, Row } from 'antd';
import './XiaoGuai.css'
import bg from './biwu.jpg';


const { Meta } = Card;

const XiaoGuai = () => {

    const { userId } = useParams();
    const [cards, setCards] = useState([]);
    const [opponentCards, setOpponentCards] = useState([]);
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState(null);
    const [selectedCard, setSelectedCard] = useState(null);
    const [selectedOpponentCard, setSelectedOpponentCard] = useState(null);
    const [ImgUrl, setImgUrl] = useState(null);//图片地址


    // const imageUrls = [
    //     'https://pic1.zhimg.com/v2-c661740055d91606880283692e40720c_r.jpg',
    //     'https://wallpaperm.cmcm.com/4700eaf249b71d56d95aff8ca94313fa.jpg',
    //     'https://pic3.zhimg.com/v2-5523ed93593ee4c7fd97b972d0af92d3_r.jpg',
    //     'https://pic1.zhimg.com/v2-3e2fe005af51c7636486d2a9a99cfb3e_r.jpg',
    //     // ... 更多图片链接
    // ];

    // const getRandomImageUrl = () => {
    //     const randomIndex = Math.floor(Math.random() * imageUrls.length);
    //     return imageUrls[randomIndex];
    // };
    const fetchCards = async () => {
        setLoading(true);
        try {
            const response = await axios.post('http://localhost:3001/getUserCards', { userId: userId });
            const data = await response.data;
            setCards(data);
        } catch (error) {
            setError(error.message);
        } finally {
            setLoading(false);
        }
    };
    useEffect(() => {
        fetchCards();
    }, [userId]);

    const generateOpponentCards = async () => {
        setLoading(true);
        try {
            let newOpponentCards = [];
            for (let i = 0; i < 3; i++) {
                const response = await axios.post('http://localhost:3001/getOpponentInfo', { userId: userId });
                const data = await response.data;
                newOpponentCards.push(data.cardInfo);
            }
            setOpponentCards(newOpponentCards);
        } catch (error) {
            setError(error.message);
        } finally {
            setLoading(false);
        }
    };

    const handleBattle = async (opponentCard) => {
        if (!selectedCard) {
            message.error('请先选择一张要出战的卡片');
            return;
        }

        const battleData = {
            userId: userId,
            cardId: selectedCard.id,
            opponentRarity: opponentCard.rarity,
            opponentAttack: opponentCard.attack,
            opponentDefense: opponentCard.defense,
            opponentHealth: opponentCard.health,
            opponentImgUrl: opponentCard.imgUrl
        };

        try {
            const response = await axios.post('http://localhost:3001/battle', battleData);
            const resultMessage = response.data;
            message.success(resultMessage);
            fetchCards()
        } catch (error) {
            message.error('战斗失败：' + error.message);
        }
    };

    if (loading) {
        return <p>Loading...</p>;
    }

    if (error) {
        return <p>Error: {error}</p>;
    }

    return (
        <div style={{
            backgroundImage: `url(${bg})`, // 设置背景图片
            // backgroundSize: 'cover', // 设置背景图片大小
            // backgroundPosition: 'center', // 设置背景图片位置
            // minHeight: '100vh', // 确保背景图片覆盖整个页面高度
            // display: 'flex',
            // justifyContent: 'center',
            // alignItems: 'center',
        }}>
            <Row>
                <Col span={12}>
                    <h2>我的卡片</h2>
                    <Row>
                        {cards.map((card) => (
                            <Card
                                key={card.id}
                                hoverable
                                style={{
                                    width: 240,
                                    marginRight: 16,
                                    marginBottom: 16
                                }}
                                onClick={() => setSelectedCard(card)}
                                className={selectedCard && selectedCard.id === card.id ? 'selected-card' : ''}
                                cover={<img alt="example" src={card.image_url} />}

                            >
                                <Meta
                                    title={card.name}
                                    description={
                                        <div>
                                            <p>Rarity: {card.rarity}</p>
                                            <p>Attack: {card.attack}</p>
                                            <p>Defense: {card.defense}</p>
                                            <p>Health: {card.health}</p>
                                            <Button type="primary" onClick={() => setSelectedCard(card)}>
                                                准备战斗
                                            </Button>
                                        </div>
                                    }
                                />
                            </Card>
                        ))}
                    </Row>
                </Col>
                <Col span={12}>
                    <h2>对手</h2>
                    <Button onClick={generateOpponentCards}>开始随机生成三个卡牌对手</Button>
                    <Row>
                        {opponentCards.map((card, index) => (
                            <Card
                                key={index}
                                hoverable
                                style={{
                                    width: 240,
                                    marginRight: 16,
                                    marginBottom: 16
                                }}
                                cover={<img alt="example" src={card.imgUrl} />}

                            >
                                <Meta
                                    title={card.name}
                                    description={
                                        <div>
                                            <p>稀有等级: {card.rarity}</p>
                                            <p>攻击力: {card.attack}</p>
                                            <p>防御力: {card.defense}</p>
                                            <p>生命值: {card.health}</p>
                                            <Button type="primary" onClick={() => handleBattle(card)}>
                                                开始战斗
                                            </Button>
                                        </div>
                                    }
                                />
                            </Card>
                        ))}
                    </Row>
                </Col>
            </Row>
        </div>
    );
};

export default XiaoGuai;
